<template>
  <div style="background-color: #fff; padding-top: 8px">
    <el-form :model="form" ref="form" label-width="100px">
      <el-form-item label="系统名称:">
        <el-tag type="success" size="medium">{{ SystemName }}</el-tag>
      </el-form-item>
      <el-form-item label="角色名称:">
        <span>{{ RoleName }}</span></el-form-item
      >
      <el-form-item label="关联人员:">
        <el-button size="medium" type="primary" @click="addData"
          >编 辑</el-button
        >
        <div class="glry">
          <el-row>
            <el-col :span="12">
              <div class="user">
                <el-tree
                  :data="data"
                  default-expand-all
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                >
                  <span slot-scope="{ node, data }" class="span__">
                    <span class="tree-node-span" v-if="data.isUser">
                      <i class="el-icon-s-custom"></i>
                      {{ node.label }}
                    </span>
                    <span v-if="!data.isUser">{{ node.label }}</span>
                  </span>
                </el-tree>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
    </el-form>
    <div style="padding: 0 18px 18px 18px"></div>
    <div style="height: 56px">
      <div style="margin: 0 18px 18px 0; float: right">
        <el-button plain @click="back">返 回</el-button>
      </div>
    </div>

    <div>
      <el-drawer
        title="选择人员"
        :visible.sync="drawer"
        direction="rtl"
        size="20%"
        :before-close="handleClose2"
      >
        <div style="width: 90%; margin: 0 auto">
          <div style="margin-bottom: 12px">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText">
            </el-input>
          </div>
          <el-checkbox
            size="mini"
            :indeterminate="isIndeterminate"
            v-model="caseCheckAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >

          <el-tree
            ref="casetree"
            :filter-node-method="filterNode"
            :data="datas"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="checkedKeys"
            :props="defaultProps"
            :check-strictly="true"
            @check-change="caseCheckChange"
          >
          </el-tree>
        </div>
        <span style="position: absolute; width: 100%; bottom: 12px">
          <el-button
            style="width: 45%; margin-left: 12px"
            @click="drawer = false"
            >取 消</el-button
          >
          <el-button
            style="width: 45%"
            type="primary"
            @click="submit"
            :loading="loading"
            >确 定</el-button
          >
        </span>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import {
  GetPermissionsUserTreeList_get,
  GetPermissionsUserTree_get,
  AddUserRole_post,
} from "@/api/business";
export default {
  name: "VueXuAdminOperate",
  watch: {
    filterText(val) {
      this.$refs.casetree.filter(val);
    },
  },
  data() {
    return {
      SystemName: JSON.parse(localStorage.getItem("xmGlDetails")).SystemName,
      RoleName: JSON.parse(localStorage.getItem("xmGlSzQx")).RoleName,
      caseCheckAll: false, //全选按钮的绑定值
      isIndeterminate: false, //全选按钮的全选，半选样式
      drawer: false,
      loading: false,
      filterText: "",
      form: {
        name: "",
        status: "",
      },
      checkedKeys: [],
      datas: [],
      ids: [],
      loading: false,
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },

  mounted() {
    this.getTreeList();
  },

  methods: {
    addData() {
      this.drawer = true;
      this.getTree();
    },
    async submit() {
      let list = this.$refs.casetree.getCheckedKeys();
      console.log(list, "list");
      let data = {
        RoleId: JSON.parse(localStorage.getItem("xmGlSzQx")).Id,
        UserId: list,
      };
      this.loding = true;
      let res = await AddUserRole_post(data);
      if (res.data.success) {
        this.loading = false;
        this.drawer = false;
        this.getTreeList();
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.loading = false;
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    async getTree() {
      let res = await GetPermissionsUserTree_get(
        JSON.parse(localStorage.getItem("xmGlSzQx")).Id
      );

      this.datas = res.data.response.UserRoleTree;
      this.checkedKeys = res.data.response.ids;
    },
    async getTreeList() {
      let res = await GetPermissionsUserTreeList_get(
        JSON.parse(localStorage.getItem("xmGlSzQx")).Id
      );
      console.log(res);
      this.data = res.data.response;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      console.log(data);
    },
    handleClose2(done) {
      this.drawer = false;
    },
    back() {
      this.$router.push({
        path: "/xmGlDetails",
      });
    },
    caseCheckChange() {
      //树节点check事件
      let checked_count = 0; //被勾选上的一级节点个数
      let disabled_count = 0; //置灰的一级节点个数
      let indeterminate_flag = false; //有没有一级节点处于半选状态
      // 深度遍历所有一级节点
      var numArray = [];
      this.ids = [];
      let stack = [...this.datas],
        node;
      while ((node = stack.shift())) {
        numArray.push(node.id);

        if (this.$refs.casetree.getNode(node).disabled == true) {
          disabled_count += 1; //如果有置灰的节点，置灰变量加1
        }
        if (this.$refs.casetree.getNode(node).checked == true) {
          checked_count += 1; //如果有勾选的节点，勾选变量加1
        }
        if (this.$refs.casetree.getNode(node).indeterminate == true) {
          indeterminate_flag = true; //如果有半选的节点，半选变量设为true
        }
        // 如果有子元素的话进行压栈操作
        if (node.children) stack.unshift(...node.children);
      }
      if (checked_count == 0) {
        this.isIndeterminate = false;
        this.caseCheckAll = false; //如果勾选的一级节点数为0，则设置全选按钮样式不为半选样式，全选的值为false
        if (indeterminate_flag == true) {
          //如果下面有半选的，设置全选按钮的样式为半选样式
          this.isIndeterminate = true;
          this.caseCheckAll = false;
        }
      } else if (checked_count + disabled_count == numArray.length) {
        //如果树上勾上的和置灰的加起来等于tree上data的长度，设置全选按钮样式不为半选样式，全选值为true
        this.isIndeterminate = false;
        this.caseCheckAll = true;
      } else {
        //上面条件不满足，则说明没有全部勾上，设置样式为半选，全选值为false
        this.isIndeterminate = true;
        this.caseCheckAll = false;
      }
      return;
    },
    handleCheckAllChange() {
      //全选按钮勾上的方法事件
      this.isIndeterminate = false; //设置全选按钮样式不为半选
      if (this.caseCheckAll == true) {
        //如果是当前值是全选，依次遍历节点设置勾选，同时过滤的disabled为true的
        // 深度遍历
        let stack = [...this.datas],
          node;
        while ((node = stack.shift())) {
          if (this.$refs.casetree.getNode(node).disabled == false) {
            this.$refs.casetree.setChecked(node.id, true, true);
          }
          // 如果有子元素的话进行压栈操作
          if (node.children) stack.unshift(...node.children);
        }
      } else {
        //当前值不是全选，设置勾选列表为空
        this.$refs.casetree.setCheckedKeys([]);
      }
    },
  },
};
</script>

<style  scoped>
/deep/.el-form-item__label {
  font-size: 16px;
}
/deep/ .el-form-item__content {
  font-size: 16px;
}
/deep/ .el-tree .el-tree-node .el-checkbox .is-disabled {
  display: none;
}
.glry {
  width: 50%;
  height: 400px;

  /* // border: 1px solid #c0c4cc; */
  border-radius: 8px;
  padding: 12px;
  /* // margin-top: 24px; */
}
.user {
  height: 400px;
  overflow: auto;
}
.tree-node-span {
  display: inline-block;
  /* // padding: 2px 4px; */
  color: #4965d2;
  font-weight: 600;
  /* // background-color: #ccc; */
}
</style>
